using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace MTRC.ODMS.Web.SOM.GeneralEvent
{
    /// <summary>
    /// author:Weiyudong
    /// </summary>
    public partial class GeneralEventEnquiry : BasePage_SOM
    {
        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M140201";
            }
        }

        #endregion

        #region Page Init And Load

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(LPOWebPageTemplate_ChangeLanguage);
            this.grdSearchResult.NeedDataBind += new APJ.Web.UI.WebControls.CommonGridView.NeedDataBindHandler(grdSearchResult_NeedDataBind);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // add by dylan 20151030 for u275.1 
                this.grdSearchResult.PageSize = this.GridViewPageDefaultSize();

                this.SetLanguage();

                this.InitializePage();
                this.hdnBoolClkBtn.Value = "YES";
                if (Request.QueryString["isBack"] != null && Request.QueryString["isBack"].Trim() != string.Empty && Convert.ToInt32(Request.QueryString["isBack"].ToString()) > 0)
                {

                }
                else
                {
                    this.BindData();
                }
                //added by Nathan 2015-08-15
                if (chkFreeTextSearch.Checked)
                {
                    txtConditionOne.Enabled = true;
                    txtConditionTwo.Enabled = true;
                    txtConditionThree.Enabled = true;
                    rdoAnd.Enabled = true;
                    rdoOr.Enabled = true;
                }
                else
                {
                    txtConditionOne.Enabled = false;
                    txtConditionTwo.Enabled = false;
                    txtConditionThree.Enabled = false;
                    rdoAnd.Enabled = false;
                    rdoOr.Enabled = false;
                    rdoAnd.Checked = true;
                }

                /*******************add by jack 20151202 for using session store enquiry condition satrt**********************/
                string isBack = Request.QueryString["isBack"];
                if (isBack == "1")
                {
                    this.ddlStation.SelectedValue = Session["Common_Station"].ToString();
                    this.dtbCreateTimeFrom.Text = Session["Common_DateFrom"].ToString();
                    this.dtbCreateTimeTo.Text = Session["Common_DateTo"].ToString();
                    this.SetCheckboxListValue(Session["Common_ShowList"].ToString(), this.chklShow);

                    //this.ddlGenCategory.SelectedValue = Session["GeneralEvent_GenCategory"].ToString();
                    //this.ddlGenSubCategory.SelectedValue = Session["GeneralEvent_GenSubCategory"].ToString();
                    if (Session["GeneralEvent_GenCategory"] != null && Session["GeneralEvent_GenCategory"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlGenCategory, Session["GeneralEvent_GenCategory"].ToString());
                        this.ddlGenCategory_SelectedIndexChanged(null, null);
                    }
                    if (Session["GeneralEvent_GenSubCategory"] != null && Session["GeneralEvent_GenSubCategory"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlGenSubCategory, Session["GeneralEvent_GenSubCategory"].ToString());
                    }

                    this.ddlGenState.SelectedValue = Session["GeneralEvent_GenState"].ToString();
                    this.ddlGenSeverity.SelectedValue = Session["GeneralEvent_GenSeverity"].ToString();
                    Boolean boolFreeTextSearch = Convert.ToBoolean(Session["Common_FreeTextSearch"]);
                    this.chkFreeTextSearch.Checked = boolFreeTextSearch;
                    if (boolFreeTextSearch)
                    {
                        this.rdoAnd.Enabled = true;
                        this.rdoOr.Enabled = true;
                        this.txtConditionOne.Enabled = true;
                        this.txtConditionTwo.Enabled = true;
                        this.txtConditionThree.Enabled = true;
                        this.TextOne.Text = Session["Common_ConditionOne"].ToString();
                        this.TextTwo.Text = Session["Common_ConditionTwo"].ToString();
                        this.TextThree.Text = Session["Common_ConditionThree"].ToString();
                    }
                    else
                    {
                        this.txtConditionOne.ReadOnly = false;
                        this.txtConditionTwo.ReadOnly = false;
                        this.txtConditionThree.ReadOnly = false;
                    }
                    this.rdoAnd.Checked = Convert.ToBoolean(Session["Common_RdoAnd"].ToString());
                    this.rdoOr.Checked = Convert.ToBoolean(Session["Common_RdoOr"].ToString());
                }
                /*******************add by jack 20151202 for using session store enquiry condition end**********************/
            }
        }
        /// <summary>
        /// init the page's items.
        /// </summary>
        private void InitializePage()
        {
            DateTime CurrentMonthTo = MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime();
            // edit by dylan 20150902 for u189 issue log
            this.dtbCreateTimeTo.SetDateTime(CurrentMonthTo.Date);
            //get date range form parm table
            string strDateRangel = DAL.CommonData.GetNumVal("SOM_GeneralEvent_EnquiryDateRange").ToString();
            if (strDateRangel.Length > 0)
            {
                DateTime CurrentMonthFrom = new DateTime();
                try
                {
                    // edit by dylan 20150902 for u189 issue log
                    CurrentMonthFrom = CurrentMonthTo.Date.AddDays(-(int.Parse(strDateRangel)));
                }
                catch
                {
                    // edit by dylan 20150902 for u189 issue log
                    CurrentMonthFrom = CurrentMonthTo.Date.AddDays(0);
                }
                this.dtbCreateTimeFrom.SetDateTime(CurrentMonthFrom);

            }
            this.FunctionItemSetting();
            this.btnExporttoExcel.Enabled = false;
            //
            this.BindGenCategory();
            this.BindGenSubCategory();
            this.BindGenState();
            this.BindGenSeverity();
            this.BindControlCheckList();
        }
        /// <summary>
        /// Access right get 
        /// </summary>
        private void FunctionItemSetting()
        {
            //update by gordon 20151020 U247
            //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
            BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
            this.ddlStation.Enabled = false;
            if (DAL.Security.User.CanFunctionItemAccess("M140201_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //BindStation
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
                this.ddlStation.Enabled = true;
            }
            if (DAL.Security.User.CanFunctionItemAccess("M140201_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
                this.ddlStation.Enabled = true;
            }


            if (DAL.Security.User.CanFunctionItemAccess("M140201_F1", this.ODMUser.UserProfileID, this.MenuID)) //readonly
            {
                this.btnNew.Enabled = false;
            }

            //update by gordon 20151020 U247
            //if (ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)
            //{
            //    this.ddlStation.SelectedValue = this.ODMUser.StationID.ToString();
            //}
            if (ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)
            {
                this.ddlStation.SelectedValue = this.ODMUser.LocationID.ToString();
            }

            /* Comment by jack 20150821 for u70 */
            //if (DAL.Security.User.CanFunctionItemAccess("M140201_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            //{

            //}
            //else if (DAL.Security.User.CanFunctionItemAccess("M140201_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            //{

            //}
            //else
            //{
            //    if (!IsValidStation(this.ODMUser.LocationID))
            //    {
            //        if (Request.QueryString["IsReject"] != "1")
            //        {
            //            this.PAlert(this.GetMessage("SOM_NotValidStation"));
            //        }
            //        this.ddlStation.Items.Clear();
            //        //return;
            //    }

            //}
            /************************************/
        }

        private void BindGenCategory()
        {

            this.BindListControl(this.ddlGenCategory, "GenCategoryID", "Description", MTRC.ODMS.DAL.SOM.CodeSetup.CDGenCategory.GetGenCategoryForEnquiry(base.LangCode), true);
            this.ddlGenCategory.SelectedIndex = 0;
        }
        private void BindGenSubCategory()
        {
            if (this.ddlGenCategory.SelectedIndex == 0)
            {
                this.BindListControl(this.ddlGenSubCategory, "GenSubCategoryID", "PDescription", MTRC.ODMS.DAL.SOM.CodeSetup.CDGenSubCategory.GetGenSubCategoryAllForEnquiry(base.LangCode), true);
                this.ddlGenSubCategory.SelectedIndex = 0;
            }
            else
            {
                string selectedValue = this.ddlGenCategory.SelectedValue;
                DataView view = new DataView();
                view.Table = MTRC.ODMS.DAL.SOM.CodeSetup.CDGenSubCategory.GetGenSubCategoryAllForEnquiry(base.LangCode);
                view.RowFilter = "GenCategoryID=" + selectedValue;
                this.BindListControl(this.ddlGenSubCategory, "GenSubCategoryID", "PDescription", view.ToTable(), true);
                if (TextGenSubCategory.Text.Trim().Length > 0)
                {
                    string subStr = TextGenSubCategory.Text;
                    ddlGenSubCategory.SelectedItem.Text = subStr;
                    TextGenSubCategory.Text = "";
                }

            }
        }
        private void BindGenState()
        {
            BindListControl(this.ddlGenState, "GenStatusID", "Description", MTRC.ODMS.DAL.SOM.CodeSetup.CDGenStatus.GetGenStatusGet(base.LangCode), true);
            this.ddlGenState.SelectedIndex = 0;
        }
        private void BindGenSeverity()
        {
            BindListControl(this.ddlGenSeverity, "GenSeverityID", "Description", MTRC.ODMS.DAL.SOM.CodeSetup.CDGenSeverity.GetGenSeverityGet(base.LangCode), true);
            this.ddlGenSeverity.SelectedIndex = 0;
        }
        private void BindControlCheckList()
        {
            BindListControl(chklShow, "EventStatusID", "Description", DAL.SOM.CodeSetup.CDEventStatus.GetActive(this.LangCode), false);
            int intShowCount = this.chklShow.Items.Count;
            for (int i = 0; i < intShowCount; i++)
            {
                if (this.chklShow.Items[i].Value == "1")
                {
                    this.chklShow.Items[i].Selected = true;
                }
            }
            if (intShowCount > 0)
            {
                this.chklShow.Items.Insert(intShowCount - 1, this.GetLabel("SOM_Handover"));
                this.chklShow.Items[intShowCount - 1].Selected = true;
            }
            else
            {
                this.chklShow.Items.Insert(0, this.GetLabel("SOM_Handover"));
                this.chklShow.Items[0].Selected = true;
            }
        }
        #endregion

        #region SetLanguage

        void LPOWebPageTemplate_ChangeLanguage(object sender, EventArgs e)
        {
            this.SetLanguage();
            this.InitializePage();
            if (this.hdnBoolClkBtn.Value == "YES")
            {
                this.BindData();
            }
        }
        /// <summary>
        /// multi language set
        /// </summary>
        private void SetLanguage()
        {
            ////
            this.lblStation.Text = this.GetLabel("SOM_Station", true);
            this.lblTimeFrom.Text = base.GetLabel("COM_From", true);
            this.lblTimeTo.Text = base.GetLabel("COM_To", true);
            this.lblShow.Text = base.GetLabel("COM_Show", true);
            this.lblGenCategory.Text = base.GetLabel("SOM_GenCategory", true);
            this.lblGenSubCategory.Text = base.GetLabel("SOM_GenSubCategory", true);
            this.lblGenState.Text = base.GetLabel("SOM_GenState", true);
            this.lblGenSeverity.Text = base.GetLabel("SOM_GenSeverity", true);
            this.btnNew.Text = base.GetLabel("SOM_AddNewAssetLoanItem");
            this.btnSearch.Text = base.GetLabel("COM_Search");
            this.btnExporttoExcel.Text = base.GetLabel("COM_Export");
            this.chkFreeTextSearch.Text = base.GetLabel("COM_FreeTextSearch", true);
            this.rdoAnd.Text = base.GetLabel("SOM_And");
            this.rdoOr.Text = base.GetLabel("SOM_Or");
        }
        /// <summary>
        /// get data from database 
        /// </summary>
        private void BindData()
        {
            /* Comment by jack 20150822 for u70 */
            if (DAL.Security.User.CanFunctionItemAccess("M140201_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {

            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140201_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {

            }
            else
            {
                if (!IsValidStation(this.ODMUser.LocationID))
                {

                    if (Request.QueryString["IsReject"] != "1")
                    {
                        this.PAlert(this.GetMessage("SOM_NotValidStation"));
                    }
                    this.ddlStation.Items.Clear();
                    DataTable dtNull = new DataTable();
                    this.grdSearchResult.DataSource = dtNull.DefaultView;
                    this.grdSearchResult.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
                    this.grdSearchResult.DataBind();
                    dtNull.Dispose();
                    return;
                }

            }
            /************************************/

            //edit by hjh 20120516 for issue 1531
            DataSet dsSearchResult = this.getData();
            if (dsSearchResult == null)
            {
                return;
            }

            //this.hdnCacheDataReturnInt.Value = BLL.SOM.TempData.CacheDataSet(dsSearchResult, this.ODMUser.ID, this.ODMUser.Domain.ToString()).ToString();
            DataTable dtSearchResult = new DataTable();
            dtSearchResult = dsSearchResult.Tables[0];
            if (dtSearchResult.Rows.Count > 0)
            {
                this.btnExporttoExcel.Enabled = true;
            }
            else
            {
                this.btnExporttoExcel.Enabled = false;
            }
            this.grdSearchResult.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            this.grdSearchResult.DataSource = dtSearchResult.DefaultView;
            this.grdSearchResult.DataBind();


            dsSearchResult.Dispose();
            dsSearchResult = null;
        }

        #endregion

        #region Event

        /// <summary>
        /// gen category changed, get genSubCategory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlGenCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindGenSubCategory();
        }

        /// <summary>
        /// main function; search button's event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                //added by Nathan 2015-08-15
                if (chkFreeTextSearch.Checked)
                {
                    //JMText();
                    TxtJM();
                }
                if (this.dtbCreateTimeFrom.Text.Trim().Length > 0 && this.dtbCreateTimeTo.Text.Trim().Length > 0)
                {
                    if (InvalidateInputDate(this.dtbCreateTimeFrom.GetDateTime(), this.dtbCreateTimeTo.GetDateTime()))
                    {
                        PAlert(this.GetMessage("COM_StartEndDate"));
                        return;
                    }
                }
                this.hdnBoolClkBtn.Value = "YES";
                BindData();
            }
            finally
            {
                //add by gordon 20150812 | For Search Wait Cursor
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "showWait('');", true);
            }
        }

        protected void BFSearc_Click(object sender, EventArgs e)
        {
            try
            {
                //added by Nathan 2015-08-15
                if (chkFreeTextSearch.Checked)
                {
                    JMText();
                }

                if (this.dtbCreateTimeFrom.Text.Trim().Length > 0 && this.dtbCreateTimeTo.Text.Trim().Length > 0)
                {
                    if (InvalidateInputDate(this.dtbCreateTimeFrom.GetDateTime(), this.dtbCreateTimeTo.GetDateTime()))
                    {
                        Alert(this.GetMessage("COM_StartEndDate"));
                        return;
                    }
                }
                this.hdnBoolClkBtn.Value = "YES";
                BindData();
            }
            finally
            {
                //add by gordon 20150812 | For Search Wait Cursor
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "showWait('');", true);
            }
        }

        /// <summary>
        /// Export result list to excel, the data get from the cacheData space
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExporttoExcel_Click(object sender, EventArgs e)
        {
            //edit by hjh 20120516 for issue 1531
            //if (this.hdnCacheDataReturnInt.Value != "0")
            //{
            //    DataSet cacheData = BLL.SOM.TempData.GetCacheData(int.Parse(this.hdnCacheDataReturnInt.Value));
            if (this.dtbCreateTimeFrom.Text.Trim().Length > 0 && this.dtbCreateTimeTo.Text.Trim().Length > 0)
            {
                if (InvalidateInputDate(this.dtbCreateTimeFrom.GetDateTime(), this.dtbCreateTimeTo.GetDateTime()))
                {
                    Alert(this.GetMessage("COM_StartEndDate"));
                    return;
                }
            }
            DataSet cacheData = this.getData();
            object limitExpCount = DAL.CommonData.GetNumVal("SOM_GeneralEventExportMAXControl");
            if (cacheData == null)
            {
                return;
            }
            else if (limitExpCount != null && cacheData.Tables[0].Rows.Count > int.Parse(limitExpCount.ToString()))//edit by hjh 20120516 for issue 1531
            {
                Alert(string.Format(this.GetMessage("SOM_ExportLimitControl"), int.Parse(limitExpCount.ToString())));
                return;
            }
            if (cacheData != null)
            {
                DataSet ds = new DataSet();
                ds = cacheData.Copy();
                cacheData.Dispose();
                cacheData = null;
                DataTable table = new DataTable();
                table = ds.Tables[0];
                table.Columns.Remove("StationEventID");
                table.Columns.Remove("HandoverNote");
                table.Columns.Remove("EventStatusID");
                table.Columns["EventNo"].ColumnName = base.GetLabel("SOM_EventNo");
                table.Columns["EventTime"].ColumnName = base.GetLabel("SOM_EventTime");
                table.Columns["GenCategoryDesc"].ColumnName = base.GetLabel("SOM_GenCategory");
                table.Columns["GenSubCategoryDesc"].ColumnName = base.GetLabel("SOM_GenSubCategory");
                table.Columns["GenStateDesc"].ColumnName = base.GetLabel("SOM_GenState");
                table.Columns["GenSeverityDesc"].ColumnName = base.GetLabel("SOM_GenSeverity");
                table.Columns["Description"].ColumnName = base.GetLabel("COM_Description");
                // add by dylan 20150724 for u133
                table.Columns["Reportedby"].ColumnName = base.GetLabel("SOM_Reportedby");
                table.Columns["EventStatusDesc"].ColumnName = base.GetLabel("COM_Status");
                table.Columns["FlagHandover"].ColumnName = base.GetLabel("SOM_Handover");
                table.Columns.Add("HighLightDesc");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (table.Rows[i]["HighLight"].ToString() == "1")
                    {
                        table.Rows[i]["HighLightDesc"] = base.GetLabel("SOM_HighLightYellow");
                    }
                    else if (table.Rows[i]["HighLight"].ToString() == "2")
                    {
                        table.Rows[i]["HighLightDesc"] = base.GetLabel("SOM_HighLightRed");
                    }
                    else
                    {
                        table.Rows[i]["HighLightDesc"] = base.GetLabel("SOM_HighLightNormal");
                    }
                }
                table.Columns.Remove("HighLight");
                table.Columns["HighLightDesc"].ColumnName = base.GetLabel("SOM_HighLight");
                /******************* add by dylan 20150723 for u133 start**********************************/
                //Common.ExportExcel_showHHMM(ds, this.Context, "GeneralEventList.xls");
                //string templateFile = Server.MapPath("~") + string.Format(@"\Template\MTRC\GeneralEventList Template.xlsx");
                string templateFilePath=APJ.Util.Utility.GetAppSetting("SOM_ExportExcelTemplatePath");
                if (templateFilePath.LastIndexOf("\\") != templateFilePath.Length - 1)
                    templateFilePath += "\\";
                string templateFile = templateFilePath + string.Format("GeneralEventList Template.xlsx"); //add by jack 20160127 ISU22 fixed for same export file name
                //string exportFile = Server.MapPath("~") + string.Format(@"\Template\MTRC\GeneralEventList.xlsx");
                string ExcelDownloadFilePath = APJ.Util.Utility.GetAppSetting("SOM_ExportExcelTempFilePath");
                if (ExcelDownloadFilePath.LastIndexOf("\\") != ExcelDownloadFilePath.Length - 1)
                    ExcelDownloadFilePath += "\\";
                string exportFile = ExcelDownloadFilePath + string.Format("GeneralEventList" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"); //add by jack 20160127 ISU22 fixed for same export file name
                //update by gordon 20150910
                //CreateExcelFile.ExportExcelWithTemplate(ds.Tables[0], templateFile, exportFile, Response);
                CreateExcelFile.ExportExcelWithTemplate(ds.Tables[0], templateFile, exportFile, Response, Page);
                /******************* add by dylan 20150723 for u133 end**********************************/
                table.Dispose();
                table = null;
                ds.Dispose();
                ds = null;
            }
            //}
        }
        /// <summary>
        /// deal the bind data, make the datagrid can display the right fields
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
            {
                ////huangyao 20081129 in MTR office
                string urlString = APJ.Util.Utility.GetHttpHost(base.Request) + "/SOM/GeneralEvent/GeneralEventEntry.aspx?StationEventID=" + this.grdSearchResult.DataKeys[e.Row.RowIndex][0].ToString();
                //((HyperLink)e.Row.Cells[0].Controls[0]).NavigateUrl = APJ.Util.Utility.GetHttpHost(base.Request) + "/SOM/GeneralEvent/GeneralEventEntry.aspx?StationEventID=" + this.grdSearchResult.DataKeys[e.Row.RowIndex][0].ToString();
                ((HyperLink)(e.Row.Cells[0].Controls[0])).NavigateUrl = "";
                ((HyperLink)(e.Row.Cells[0].Controls[0])).Font.Bold = true;
                string strScript = "OpenEntryPageMaximum('" + urlString + "');";
                ((HyperLink)(e.Row.Cells[0].Controls[0])).Attributes.Add("onclick", strScript);
                //----------------------------
                ((HyperLink)e.Row.Cells[0].Controls[0]).Target = "_blank";
                /******************* modified by dylan 20150723 for u133 start*****************************************************/
                if (e.Row.Cells[6].Text.Contains("\n"))
                {
                    e.Row.Cells[6].Text = e.Row.Cells[6].Text.Replace("\n", "<br>");
                }
                if (((DataBoundLiteralControl)e.Row.Cells[8].Controls[0]).Text.Contains("1"))
                {
                    ((Image)e.Row.Cells[9].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/EventStatus_OS.gif";
                    //((Image)e.Row.Cells[8].Controls[1]).ToolTip = base.GetLabel("SOM_OS", false);
                }
                else if (((DataBoundLiteralControl)e.Row.Cells[8].Controls[0]).Text.Contains("2"))
                {
                    ((Image)e.Row.Cells[9].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/EventStatus_COM.gif";
                    // ((Image)e.Row.Cells[8].Controls[1]).ToolTip = base.GetLabel("SOM_Completed", false);
                }
                else
                {
                    ((Image)e.Row.Cells[9].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/EventStatus_Void.gif";
                    //((Image)e.Row.Cells[8].Controls[1]).ToolTip = base.GetLabel("SOM_Void", false);
                }
                if (((DataBoundLiteralControl)e.Row.Cells[10].Controls[0]).Text.Contains("True"))
                {
                    ((Image)e.Row.Cells[11].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/EventHandOver.gif";
                    ((Image)e.Row.Cells[11].Controls[1]).ToolTip = ((Label)e.Row.Cells[14].FindControl("lblHandoverNote")).Text.Trim().Replace("\r\n", "");
                }
                else
                {
                    // edit by dylan 20150820 for u81.1
                    string HandOverNote = ((Label)e.Row.Cells[14].FindControl("lblHandoverNote")).Text;
                    if (!string.IsNullOrEmpty(HandOverNote))
                    {
                        ((Image)e.Row.Cells[11].Controls[1]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventHandOverDone.jpg";
                        ((Image)e.Row.Cells[11].Controls[1]).ToolTip = HandOverNote.Replace("\r\n", "");
                    }
                    else
                    {
                        ((Image)e.Row.Cells[11].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/spacer.gif";
                    }
                }
                if (((DataBoundLiteralControl)e.Row.Cells[12].Controls[0]).Text.Contains("1"))
                {
                    ((Image)e.Row.Cells[13].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/HighLight_Yellow.gif";
                    ((Image)e.Row.Cells[13].Controls[1]).ToolTip = base.GetLabel("SOM_HighLightYellow");
                }
                else if (((DataBoundLiteralControl)e.Row.Cells[12].Controls[0]).Text.Contains("2"))
                {
                    ((Image)e.Row.Cells[13].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/HighLight_Red.gif";
                    ((Image)e.Row.Cells[13].Controls[1]).ToolTip = base.GetLabel("SOM_HighLightRed");
                }
                else
                {
                    ((Image)e.Row.Cells[13].Controls[1]).ImageUrl = base.Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                    ((Image)e.Row.Cells[13].Controls[1]).ToolTip = base.GetLabel("SOM_HighLightNormal");
                }
                /******************* modified by dylan 20150723 for u133 end*********************************************************/

            }
        }

        /// <summary>
        /// //for multi page 
        /// </summary>
        protected void grdSearchResult_NeedDataBind()
        {
            this.BindData();
        }
        #endregion

        public string FormatEventTimeInGrid(string str)
        {
            if (str.Trim().Length > 0)
            {
                str = this.FormatDateTime_AddBR(str);
            }

            return str;
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect("GeneralEventEntry.aspx");
        }

        private DataSet getData()
        {
            if (this.ddlGenCategory.Items.Count == 0 || this.ddlGenSubCategory.Items.Count == 0 || this.ddlGenSeverity.Items.Count == 0 || this.ddlGenState.Items.Count == 0)
            {
                return null;
            }
            string stationIDs = "";
            int intAndOR = -1;
            string strConditionOne = string.Empty;
            string strConditionTwo = string.Empty;
            string strConditionThree = string.Empty;
            if (chkFreeTextSearch.Checked)
            {
                intAndOR = this.rdoAnd.Checked ? 1 : 0;
                strConditionOne = txtConditionOne.Text;
                strConditionTwo = txtConditionTwo.Text;
                strConditionThree = txtConditionThree.Text;
            }

            bool StatusCom = false;
            bool StatusOS = false;
            bool StatusHandover = false;
            bool StatusVoid = false;
            for (int i = 0; i < this.chklShow.Items.Count; i++)
            {
                if (this.chklShow.Items[i].Selected)
                {
                    if (this.chklShow.Items[i].Value == "2")
                    {
                        StatusCom = true;
                    }
                    else if (this.chklShow.Items[i].Value == "1")
                    {
                        StatusOS = true;
                    }
                    else if (this.chklShow.Items[i].Value == "3")
                    {
                        StatusVoid = true;
                    }
                    else
                    {
                        StatusHandover = true;
                    }
                }
            }
            //get staion list which the user can access
            SetStationSelectedItem(ref stationIDs, this.ddlStation);
            //get results
            DataSet dsSearchResult = MTRC.ODMS.BLL.SOM.Event.StationEventGeneralEvent.GetGeneralEventEnquiry(stationIDs,
                                                                                                             base.LangCode,
                                                                                                             this.dtbCreateTimeFrom.GetDateTime(),
                                                                                                             this.dtbCreateTimeTo.GetDateTime(),
                                                                                                             StatusCom,
                                                                                                             StatusOS,
                                                                                                             StatusHandover,
                                                                                                             StatusVoid,
                                                                                                             Convert.ToInt32(this.ddlGenCategory.SelectedValue),
                                                                                                             Convert.ToInt32(this.ddlGenSubCategory.SelectedValue),
                                                                                                             Convert.ToInt32(this.ddlGenState.SelectedValue),
                                                                                                             Convert.ToInt32(this.ddlGenSeverity.SelectedValue),
                                                                                                             intAndOR,
                                                                                                             strConditionOne,
                                                                                                             strConditionTwo,
                                                                                                             strConditionThree
                                                                                                             );
            return dsSearchResult;
        }

        #region added by Nathan 2015-08-15


        /// <summary>
        /// Encryption
        /// </summary>
        public void TxtJM()
        {
            if (txtConditionOne.Text.Trim().Length > 0)
            {
                string str = txtConditionOne.Text;
                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->TxtConditionOne->Before Encrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                string strJM = APJ.Util.Utility.AESEncrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->TxtConditionOne->After Encrypt:" + strJM, 4, ODMUser.ID, ODMUser.UserGroupName);

                TextOne.Text = strJM;
            }
            else
            {
                TextOne.Text = "";
            }
            if (txtConditionTwo.Text.Trim().Length > 0)
            {
                string str = txtConditionTwo.Text;
                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->TxtConditionTwo->Before Encrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                string strJM = APJ.Util.Utility.AESEncrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->TxtConditionTwo->After Encrypt:" + strJM, 4, ODMUser.ID, ODMUser.UserGroupName);
                TextTwo.Text = strJM;
            }
            else
            {
                TextTwo.Text = "";
            }
            if (txtConditionThree.Text.Trim().Length > 0)
            {
                string str = txtConditionThree.Text;
                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->TxtConditionThree->Before Encrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                string strJM = APJ.Util.Utility.AESEncrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->TxtConditionThree->After Encrypt:" + strJM, 4, ODMUser.ID, ODMUser.UserGroupName);
                TextThree.Text = strJM;
            }
            else
            {
                TextThree.Text = "";
            }

        }

        /// <summary>
        /// Decryption
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public void JMText()
        {
            if (TextOne.Text.Trim().Length > 0 && txtConditionOne.Text.Trim().Length <= 0)
            {
                string str = TextOne.Text;

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->txtConditionOne->Before Decrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                txtConditionOne.Text = APJ.Util.Utility.AESDecrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->txtConditionOne->After Decrypt:" + txtConditionOne.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

                // TextOne.Text = "";
            }
            if (TextTwo.Text.Trim().Length > 0 && txtConditionTwo.Text.Trim().Length <= 0)
            {
                string str = TextTwo.Text;

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->txtConditionTwo->Before Decrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                txtConditionTwo.Text = APJ.Util.Utility.AESDecrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->txtConditionTwo->After Decrypt:" + txtConditionTwo.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

                //TextTwo.Text = "";
            }
            if (TextThree.Text.Trim().Length > 0 && txtConditionThree.Text.Trim().Length <= 0)
            {
                string str = TextThree.Text;

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("GE->txtConditionThree->Before Decrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                txtConditionThree.Text = APJ.Util.Utility.AESDecrypt(str);

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("GE->txtConditionThree->After Decrypt:" + txtConditionThree.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

                //TextThree.Text = "";
            }
        }

        protected void chkFreeTextSearch_CheckedChanged(object sender, EventArgs e)
        {
            if (chkFreeTextSearch.Checked)
            {
                txtConditionOne.Enabled = true;
                txtConditionTwo.Enabled = true;
                txtConditionThree.Enabled = true;
                rdoAnd.Enabled = true;
                rdoOr.Enabled = true;

            }
            else
            {
                txtConditionOne.Enabled = false;
                txtConditionTwo.Enabled = false;
                txtConditionThree.Enabled = false;
                rdoAnd.Enabled = false;
                rdoOr.Enabled = false;

                txtConditionOne.Text = "";
                txtConditionTwo.Text = "";
                txtConditionThree.Text = "";
                TextOne.Text = "";
                TextTwo.Text = "";
                TextThree.Text = "";
            }

            if (TextRadio.Text.Trim().Length > 0)
            {
                if (TextRadio.Text.Trim() == "2")
                {
                    rdoAnd.Checked = false;
                    rdoOr.Checked = true;
                }
                else
                {
                    rdoAnd.Checked = true;
                    rdoOr.Checked = false;
                }
            }
        }
        #endregion added by Nathan 2015-08-15

        /// <summary>
        ///  add by jack 20151202 for using session store enquiry condition
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSetSession_Click(object sender, EventArgs e)
        {
            this.RemoveCommonSession();

            string Url = this.HiddenFieldUrl.Value;
            Session["Common_Station"] = this.ddlStation.SelectedValue.ToString();
            Session["Common_DateFrom"] = this.dtbCreateTimeFrom.Text.ToString();
            Session["Common_DateTo"] = this.dtbCreateTimeTo.Text.ToString();
            Session["Common_ShowList"] = this.GetCheckboxListValue(this.chklShow);
            Session["GeneralEvent_GenCategory"] = this.ddlGenCategory.SelectedValue;
            Session["GeneralEvent_GenSubCategory"] = this.ddlGenSubCategory.SelectedValue;
            Session["GeneralEvent_GenState"] = this.ddlGenState.SelectedValue;
            Session["GeneralEvent_GenSeverity"] = this.ddlGenSeverity.SelectedValue;
            Session["Common_FreeTextSearch"] = this.chkFreeTextSearch.Checked;
            Session["Common_ConditionOne"] = this.TextOne.Text.ToString();
            Session["Common_ConditionTwo"] = this.TextTwo.Text.ToString();
            Session["Common_ConditionThree"] = this.TextThree.Text.ToString();
            Session["Common_RdoAnd"] = this.rdoAnd.Checked;
            Session["Common_RdoOr"] = this.rdoOr.Checked;
            Response.Redirect(Url + "&isBack=1&PageID=GeneralEventEnquiry");
        }
    }
}
